import { getTags } from "@/api/question";
import { addPosts } from "@/api/user";
import { Button, Input, Select, message } from "antd";
import Editor from "for-editor";
import { useEffect, useState } from "react";
const Publish = () => {
  const [editorValue, setEditorValue] = useState("");
  const [title, setTitle] = useState("");
  const [tags, setTags] = useState<any[]>([]);
  const [selectTags, setSelectTags] = useState([]);

  const handleAddPosts = () => {
    if (!title) {
      message.error("标题不能为空！！！");
      return;
    }
    if (!editorValue) {
      message.error("内容不能为空！！！");
      return;
    }
    if (selectTags.length <= 0) {
      message.error("标签不能为空！！！");
      return;
    }
    const userID = sessionStorage.getItem("userID");
    addPosts({
      userID,
      title,
      tags: JSON.stringify(selectTags),
      content: editorValue,
    }).then(() => {
      message.success("发布成功!");
    });
  };

  useEffect(() => {
    getTags().then((tags) => {
      setTags(
        tags.map((it) => ({
          label: it.tagName,
          value: it.tagName,
        }))
      );
    });
  }, []);

  return (
    <div>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "10px",
        }}
      >
        <div style={{ display: "flex", alignItems: "center" }}>
          <div>标题：</div>
          <Input
            style={{ width: "600px" }}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="请输入标题"
          />
          <Select
            mode="tags"
            placeholder="请选择标签"
            options={tags}
            onChange={(tags) => setSelectTags(tags)}
            style={{ marginLeft: "20px", width: "200px" }}
          />
        </div>
        <Button type="primary" onClick={handleAddPosts}>
          发布
        </Button>
      </div>
      <Editor
        subfield={true}
        preview={true}
        value={editorValue}
        onChange={(value) => setEditorValue(value)}
      />
    </div>
  );
};

export default Publish;
